<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片转换工具</title>
	<style>
		.upload_warp_img_div_del {
		  position: absolute;
		  top: 6px;
		  width: 16px;
		  right: 4px;
		}

		.upload_warp_img_div_top {
		  position: absolute;
		  top: 0;
		  width: 100%;
		  height: 30px;
		  background-color: rgba(0, 0, 0, 0.4);
		  line-height: 30px;
		  text-align: left;
		  color: #fff;
		  font-size: 12px;
		  text-indent: 4px;
		}

		.upload_warp_img_div_text {
		  white-space: nowrap;
		  width: 80%;
		  overflow: hidden;
		  text-overflow: ellipsis;
		}

		.upload_warp_img_div img {
		  max-width: 100%;
		  max-height: 100%;
		  vertical-align: middle;
		}

		.upload_warp_img_div {
		  position: relative;
		  height: 100px;
		  width: 120px;
		  border: 1px solid #2196F3;
		  margin: 0px 30px 10px 0px;
		  float: left;
		  line-height: 100px;
		  display: table-cell;
		  text-align: center;
		  background-color: #eee;
		  cursor: pointer;
		}

		.upload_warp_img {
		  border-top: 1px solid #D2D2D2;
		  padding: 14px 0 0 14px;
		  overflow: hidden
		}

		.upload_warp_text {
		  text-align: left;
		  margin-bottom: 10px;
		  padding-top: 10px;
		  text-indent: 14px;
		  border-top: 1px solid #2196F3;
		  font-size: 14px;
		}

		.upload_warp_right {
		  float: left;
		  width: 56%;
		  margin-left: 2%;
		  height: 100%;
		  border: 2px dashed #2196F3;
		  border-radius: 4px;
		  line-height: 130px;
		  color: #2196F3;
		}

		.upload_warp_left img {
		  margin-top: 32px;
		}

		.upload_warp_left {
		  float: left;
		  width: 40%;
		  height: 100%;
		  border: 2px dashed #2196F3;
		  border-radius: 4px;
		  cursor: pointer;
		}

		.upload_warp {
		  margin: 14px;
		  height: 130px;
		}

		.upload {
		  border: 1px solid #2196F3;
		  background-color: #fff;
		  width: 800px;
		  border-radius: 4px;
		}

		.hello {
		  width: 800px;
		  margin-left: 27%;
		  text-align: center;
		}
		.ml20{
			margin-left: 20px;
		}
		.c-red{
			color: red;
		}
		body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh; /* 使整个页面高度可用 */
            margin: 0; /* 移除默认的边距 */
            padding: 20px; /* 添加一些内边距 */
            box-sizing: border-box; /* 确保内边距不会增加总宽度 */
        }

        h1 {
            text-align: center; /* 标题居中 */
            margin-bottom: 50px; /* 与下方内容之间的间距 */
        }

        .container {
            display: flex;
            align-items: center; /* 垂直居中 */
            width: 100%; /* 设置宽度以应用内边距 */
            max-width: 800px; /* 限制最大宽度，防止过宽 */
        }

        .file-input {
            flex: 0 0 20%; /* 文件选择固定宽度 */
            text-align: center; /* 文本居中 */
        }

        .details {
            display: flex;
            flex-direction: column;
            flex: 1; /* 剩余空间 */
            align-items: flex-start; /* 文本对齐方式 */
        }

        .details > label {
            margin-bottom: 5px; /* 标签下方的外边距 */
        }

        .buttons {
            display: flex;
            flex-direction: column;
            flex: 0 0 20%; /* 按钮列固定宽度 */
            justify-content: space-between; /* 按钮垂直分布 */
        }

        /* 额外的样式 */
        input[type="file"], input[type="radio"], button {
            margin-right: 5px; /* 输入框与标签之间的间距 */
        }
		
		.prettyButton {
			background-color: #4CAF50; /* 绿色背景 */
		  	border: none;
			color: white;
			padding: 15px 32px;
			text-align: center;
			text-decoration: none;
			display: inline-block;
			font-size: 16px;
			margin: 4px 2px;
			cursor: pointer;
			border-radius: 8px; /* 圆角边框 */
			transition: all 0.3s; /* 动画过渡效果 */
		}
		/* disabled状态的prettyButton样式 */
		.prettyButton[disabled] {
			background-color: #CCCCCC; /* 灰色背景 */
			color: #888888; /* 灰色文字 */
			cursor: not-allowed; /* 禁止鼠标悬停样式 */
			opacity: 0.6; /* 降低透明度 */
		}
 
		.prettyButton:hover {
		  background-color: #45a049; /* 悬停时的绿色 */
		}
	</style>
</head>
<body>
	<div id="app">
	  		<div class="upload">
		  <div class="upload_warp">
			<div class="upload_warp_left" @click="fileClick">
			  <img src="img/upload.png">
			</div>
			<div class="upload_warp_right" @drop="drop($event)" @dragenter="dragenter($event)" @dragover="dragover($event)">
			  或者将文件拖到此处
			</div>
		  </div>
		  <div class="upload_warp_text">
			选中{{imgList.length}}个文件，共{{bytesToSize(this.size)}}
			<span class="ml20 c-red">[单个附件的最大不超过10MB]</span>
		  </div>
		  <input @change="fileChange($event)" type="file" id="upload_file" accept="image/*" multiple style="display: none">
		  <div class="upload_warp_img" v-show="imgList.length!=0">
			<div class="upload_warp_img_div" v-for="(item,index) of imgList">
			  <div class="upload_warp_img_div_top">
				<div class="upload_warp_img_div_text">
				  {{item.file.name}}
				</div>
				<img src="img/del.png" class="upload_warp_img_div_del" @click="fileDel(index)">
			  </div>
			  <img :src="item.file.src">
			</div>
		  </div>
		</div>
	          <div class="details">
            <div>
			    <br>
                <label>类型:</label>
                <input type="radio" name="format" value="ico" checked> ico
                <input type="radio" name="format" value="bmp"> bmp
            </div>
            <div id="sizeContainer" >
			 <br>
                <label>大小:</label>
                <input type="radio" name="size" value="32"> 32x32
                <input type="radio" name="size" value="48" checked > 48x48
				<input type="radio" name="size" value="64"> 64x64
				<input type="radio" name="size" value="128"> 128x128
				<input type="radio" name="size" value="256"> 256x256
            </div>
					 <br>
        </div>

        <div class="buttons">
            <button id="convertButton" class="prettyButton">转换</button>
            <br>
            <button id="downloadButton" disabled class="prettyButton">下载</button>
            <a id="downloadLink" style="display: none;"></a>

        </div>
	</div>
	<script src="js/vue.min.js"></script>
	<script>
	  var app = new Vue({
		el: '#app',
		data () {
		  return {
			imgList: [],
			size: 0
		  }
		},
		methods: {
		  fileClick(){
			document.getElementById('upload_file').click()
		  },
		  fileChange(el){
			if (!el.target.files[0].size) return;
			this.fileList(el.target.files);
			el.target.value = ''
		  },
		  fileList(files){
			  if (files.length>1) {
				  alert('一次只能选择一张图片')
			  }else {
				  this.fileAdd(files[0])
			  }
			// for (let i = 0; i < files.length; i++) {
			//   this.fileAdd(files[i]);
			// }
		  },
		  fileAdd(file){
			  if (this.imgList.length > 0) {
				  alert('一次只能转换一张图片')
			  }else {
				  this.size = this.size + file.size;//总大小
				  let reader = new FileReader();
				  reader.vue = this;
				  reader.readAsDataURL(file);
				  reader.onload = function () {
					  file.src = this.result;
					  this.vue.imgList.push({
						  file
					  });
				  }
			  }
		  },
		  fileDel(index){
			this.size = this.size - this.imgList[index].file.size;//总大小
			this.imgList.splice(index, 1);
		  },
		  bytesToSize(bytes){
			if (bytes === 0) return '0 B';
			let k = 1000, // or 1024
			  sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
			  i = Math.floor(Math.log(bytes) / Math.log(k));
			return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
		  },
		  dragenter(el){
			el.stopPropagation();
			el.preventDefault();
		  },
		  dragover(el){
			el.stopPropagation();
			el.preventDefault();
		  },
		  drop(el){
			el.stopPropagation();
			el.preventDefault();
			this.fileList(el.dataTransfer.files);
		  }
		}
	  })
	  
	  
	    document.addEventListener('DOMContentLoaded', function() {
            var formatRadios = document.querySelectorAll('input[name="format"]');
            var sizeContainer = document.getElementById('sizeContainer');
            var convertButton = document.getElementById('convertButton');

            // 监听格式选择框的变化
            formatRadios.forEach(function(radio) {
                radio.addEventListener('change', function() {
                    if (this.value === 'bmp') {
                        sizeContainer.style.display = 'none'; // 隐藏大小选择框
                    } else {
                        sizeContainer.style.display = 'block'; // 显示大小选择框
                    }
                });
            });

            // 转换按钮点击事件
            convertButton.addEventListener('click', function() {
             
                var file = app.$data.imgList[0].file
                var format = document.querySelector('input[name="format"]:checked').value;
                var sizeInput = document.querySelector('input[name="size"]:checked');
                var size = sizeInput ? sizeInput.value : 'default'; // 如果sizeInput存在，则获取其值，否则使用默认值

                if (!file) {
                    alert('请先选择一个文件！');
                    return;
                }

                var formData = new FormData();
                formData.append('file', file);
                formData.append('type', format);
                formData.append('size', size); // 总是添加size参数，后端根据format处理

                uploadFile(formData);
            });

            // 文件上传函数
            function uploadFile(formData) {
                fetch('/api/image/convert', {
                    method: 'POST',
                    body: formData
                }).then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                }).then(data => {
                    if (data.err) {
                        alert('错误：' + data.err);
                        return;
                    }else {
                        // 设置下载链接和启用下载按钮的逻辑（如果有的话）
                        document.getElementById('downloadLink').href = '/api/image/download/' + data.dat + '?source=' +app.$data.imgList[0].file.name ;
                        document.getElementById('downloadButton').disabled = false;

                    }
                }).catch(error => {
                    console.error('Error:', error);
                    alert('文件转换失败，请重试。' + decodeURIComponent(error));
                });
            }

            document.getElementById('downloadButton').addEventListener('click', function() {
                var downloadLink = document.getElementById('downloadLink');
                // 确保下载链接存在且有效
                if (downloadLink && downloadLink.href) {
                    // 模拟点击下载链接
                    downloadLink.click();
					document.getElementById('downloadLink').href = '';
					document.getElementById('downloadButton').disabled = true;
                } else {
                    alert('下载链接无效或不存在！');
                }
            });
        });
	</script>
</body>
</html>